from backend import models
import os,sys
from concurrent.futures import ThreadPoolExecutor
import paramiko


base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(base_dir)
os.environ.setdefault("DJANGO_SETTINGS_MODULE",'untitled2.settings')

import django
django.setup()
pool=ThreadPoolExecutor(20)
def start(host_obj,cmd):
    ssh=paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    try:
        ssh.connect(username=host_obj.host.userinfo.username,password=host_obj.host.userinfo.password,hostname=host_obj.host.host.ip,\
                port=host_obj.host.host.port)
        stdin,stdout,stderr=ssh.exec_command(cmd)


    except Exception as e:
        host_obj.status=2
        host_obj.res=e
        host_obj.save()
        ssh.close()

    else:
        host_obj.status=1
        host_obj.res=stdout.read().decode('utf-8')
        host_obj.save()
        ssh.close()

def cmd(task_obj):
    command=task_obj.content
    obj=task_obj.task_res_set.all()
    for host in obj:
        pool.submit(start,host,command,)



